package com.heisenhub.common.oauth.interceptor;

import com.heisenhub.common.oauth.enums.RESTAPI;
import com.heisenhub.common.oauth.hander.ApiResourceOpenHander;
import com.heisnenhub.common.module.constant.GateWayConstant;
import com.heisnenhub.common.module.constant.HttpConstant;
import com.heisnenhub.common.module.utils.Api;
import com.heisnenhub.common.module.utils.HubObjectUtils;
import com.heisnenhub.common.module.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author sen
 * @description
 * @date 2023/12/19 14:59
 */
@Slf4j
public class XmServerProtectInterceptor implements HandlerInterceptor {



    /**
     *  效验请求头   判断有没有走网关
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws IOException
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String requestURI = request.getRequestURI();
        // 从请求头中获取是不是feign 接口请求过来的
        String interiorToken = request.getHeader(GateWayConstant.INTERIOR_HEADER_KEY);
        if (HubObjectUtils.isEmpty(interiorToken)) {
            String[] handle = ApiResourceOpenHander.apiPathCache.get(RESTAPI.INTERIOR);
            if (Arrays.stream(handle).anyMatch(requestURI::equals)){
                ResponseUtils.makeResponse(response,MediaType.APPLICATION_JSON_UTF8_VALUE,HttpServletResponse.SC_OK, Api.fail("内部接口不能直接请求"));
                return false;
            }
            return true;
        }
        // 从请求头中获取 Zuul Token
        String token = request.getHeader(GateWayConstant.ZUUL_TOKEN_HEADER);
        String zuulToken = new String(Base64Utils.encode(GateWayConstant.ZUUL_TOKEN_VALUE.getBytes()));
        // 校验 Zuul Token的正确性
        if (HubObjectUtils.equals(zuulToken, token)) {
            return true;
        } else {
            ResponseUtils.makeResponse(response,MediaType.APPLICATION_JSON_UTF8_VALUE,HttpServletResponse.SC_OK, Api.fail(HttpConstant.HttpMsg.MSG_SERVICE_NO_GETAWAY));
            return false;
        }
    }
}
